// src\stores\machine.ts
import { defineStore } from 'pinia';
import axios from '@/plugins/axios';
import { ElMessage } from 'element-plus';
import { fi } from 'element-plus/es/locale';

export const useMachineStore = defineStore('machine', {
  state: () => ({
    machines: [] as any[],
    statistics: {
      typeDistribution: [],
      statusDistribution: [],
      usageFrequency: [],
      failureRate: [],
    },
    filters: {
      startDate: '2000-01-01',
      endDate: '2999-01-01',
      ownerId: '',
      machineCategory: '',
      machineName: '',
      machineNumber: '',
    },
  }),
  actions: {
    async fetchStatistics() {
      try {
        const response = await axios.get('/machine/stats', this.filters);
        if (response.data.code === 200) {
          this.statistics = response.data.data;
        } else {
          ElMessage.error(response.data.message);
        }
      } catch (error) {
        ElMessage.error(error.message);
      }
    },
    async fetchMachines() {
      try {
        const response = await axios.post('/machine/list', this.filters);
        if (response.data.code === 200) {
          this.machines = response.data.data;
        } else {
          ElMessage.error(response.data.message);
        }

      } catch (error) {
        ElMessage.error(error.message);
      }

    },
    async addMachine(machine: any) {
      try {
        const response = await axios.post('/machine/add', machine);
        if (response.data.code === 200) {
          this.machines.push(response.data.data);
          return response.data.data;
        }
        else {
          ElMessage.error(response.data.message);
        }
      } catch (error) {
        ElMessage.error(error.message);
      }
    },
    async updateMachine(machine: any) {
      const response = await axios.put('/machine/update', machine);
      if (response.data.code === 200) {
        const index = this.machines.findIndex(m => m.id === machine.id);
        if (index !== -1) {
          this.machines[index] = response.data.data;
        }
        return response.data.data;
      }
      throw new Error('更新失败');
    },
    async deleteMachine(id: number) {
      const response = await axios.delete(`/machine/delete/${id}`);
      if (response.data.code === 200) {
        this.machines = this.machines.filter(m => m.id !== id);
      }
    },
    setFilters(filters: Partial<typeof this.filters>) {
      this.filters = { ...this.filters, ...filters };
    },
    clearFilters() {
      this.filters = { startDate: '', endDate: '', ownerId: '', machineCategory: '', machineName: '', machineNumber: '' };
    },
  },
});